<template>
  <d2-container type="full">
    <mk-search-form :model="query" @search="getData()">
      <el-form-item class="inline-item" prop="dayDate">
        <el-date-picker v-model.trim="query.selMonth" type="month" size="mini" value-format="yyyy-MM" clearable
          placeholder="选择月份">
        </el-date-picker>
      </el-form-item>
    </mk-search-form>
    <div class="table-operate">
      <el-button size="mini" icon="el-icon-upload" @click="exportEcx">导出</el-button>
    </div>
    <!-- {{ dayArr }} -->
    <!-- {{ tableData }} -->

    <el-table ref="dayArrtable" :data="dayArr" :height="heightL" style="margin-top: 20px" id="tablearrdata">
      <el-table-column prop="day" :label="query.selMonth.slice(-2) + '月'" min-width="100" align="center" fixed="left">
        <template slot-scope="scope">
          {{ scope.row.day }}日
        </template>
      </el-table-column>
      <template v-for="(item, index) in tableData">
        <el-table-column :label="shopList[index]" align="center">
          <el-table-column label="余额" align="center">
            <el-table-column :prop="`${index}-sportAtThatTime`" label="体彩机" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].sportAtThatTime) ? item[scope.row.day -
                  1].sportAtThatTime : '--' }}
              </template>
            </el-table-column>
            <el-table-column :prop="`${index}-luckyAtThatTime`" label="福彩机" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].luckyAtThatTime) ? item[scope.row.day -
                  1].luckyAtThatTime : '--' }}
              </template>
            </el-table-column>
            <el-table-column :prop="`${index}-scratchCardAtThatTime`" label="刮卡" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].scratchCardAtThatTime) ? item[scope.row.day -
                  1].scratchCardAtThatTime : '--' }}
              </template>
            </el-table-column>
            <el-table-column :prop="`${index}-dayBalanceMoney`" label="现金" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].dayBalanceMoney) ? item[scope.row.day -
                  1].dayBalanceMoney : '--' }}
              </template>
            </el-table-column>
            <el-table-column :prop="`${index}-dayBalanceWechat`" label="微信" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].dayBalanceWechat) ? item[scope.row.day -
                  1].dayBalanceWechat : '--' }}
              </template>
            </el-table-column>
            <el-table-column :prop="`${index}-subtotalOfDeposit`" label="小计" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].subtotalOfDeposit) ? KeepTwo(item[scope.row.day -
                  1].subtotalOfDeposit) : '--' }}
              </template>
            </el-table-column>
            <!--            <el-table-column :prop="`${index}-dayBalanceAlipay`" label="支付宝" align="center" min-width="75">-->
            <!--              <template slot-scope="scope">-->
            <!--                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].dayBalanceAlipay) ? item[scope.row.day - 1].dayBalanceAlipay:'&#45;&#45;' }}-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column :prop="`${index}-dayBalancePaymentCode`" label="收款码" align="center" min-width="75">-->
            <!--              <template slot-scope="scope">-->
            <!--                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].dayBalancePaymentCode) ? item[scope.row.day - 1].dayBalancePaymentCode:'&#45;&#45;' }}-->
            <!--              </template>-->
            <!--            </el-table-column>-->
          </el-table-column>
        </el-table-column>
        <el-table-column min-width="40" class-name="occupy-black" align="center"></el-table-column>
      </template>
      <el-table-column prop="total" label="压款总额" align="center" min-width="75">
        <el-table-column prop="total" label="刮卡压款" align="center" min-width="75">
          <template slot-scope="scope">
            {{ totalList[scope.row.day - 1].scratchCard || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="total" label="刮卡占比" align="center" min-width="75">
          <template slot-scope="scope">
            {{ percentageConversion(totalList[scope.row.day - 1].Proportion) || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="total" label="压款总额" align="center" min-width="75">
          <template slot-scope="scope">
            {{ KeepTwo(totalList[scope.row.day - 1].totalNumber) || '--' }}
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
  </d2-container>
</template>

<script>
import { getUnderpaymentStatistics, getUnderpaymentStatisticsTotal } from '@/api/modules/sys.report.api'
import Tools from '@/libs/utils.tool'

import { exportExecl } from '@/libs/util.export'
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  name: 'index',
  data() {
    return {
      query: {
        selMonth: Tools.fmtLong2DateTime(new Date(), 'yyyy-MM')
      },
      dayArr: [],
      tableData: [],
      totalList: [],
      shopList: [],
      heightL: null
    }
  },
  created() {
    this.getData()
    this.getWinHeight()
  },
  methods: {
    // 获取所有数据
    async getData() {
      // 清空表单值
      this.tableData = []
      this.dayArr = []
      this.totalList = []

      // 清空表单值
      const date = new Date(this.query.selMonth)
      date.setDate(1)
      const firstDay = date.toLocaleDateString()
      const dateEnd = new Date(this.query.selMonth)
      dateEnd.setMonth(dateEnd.getMonth() + 1)
      dateEnd.setDate(0)
      const lastDay = dateEnd.toLocaleDateString()
      // 所有数据
      let res = await getUnderpaymentStatistics({
        startTime: `"${firstDay}"`,
        endTime: `"${lastDay}"`
      })
      let shopList = []
      let retArr = []
      // 将不同的店区分开
      res.map(item => {
        if (shopList.includes(item.shop)) {
          retArr[shopList.indexOf(item.shop)].push(item)
        } else {
          shopList.push(item.shop)
          retArr.push([item])
        }
      })

      // 合计数据
      let resTotal = await getUnderpaymentStatisticsTotal({
        startTime: `"${firstDay}"`,
        endTime: `"${lastDay}"`
      })

      this.shopList = shopList
      this.handleData(retArr, resTotal)
    },
    // 数据处理
    handleData(res, resTotal) {
      // 获取本月总共多少天
      // const days = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate()

      const days = new Date(new Date(this.query.selMonth).getFullYear(), new Date(this.query.selMonth).getMonth() + 1, 0).getDate()
      // 创建本月所有的天
      for (let i = 1; i <= days; i++) {
        this.dayArr.push({ day: i })
        let temp = {}
        // 处理销售总额
        for (let j = 0; j < resTotal.length; j++) {
          if (Number(Tools.fmtLong2DateTime(resTotal[j].dayDate, 'dd')) === i) {
            temp = resTotal[j]
            break
          }
        }
        this.totalList.push(temp)
      }
      // 处理数据将每一个店的时间对应上列
      const tableData = []

      res.map(dayData => {
        const oneDay = []
        for (let i = 1; i <= days; i++) {
          let temp = { day: i }
          for (let j = 0; j < dayData.length; j++) {
            if (Number(Tools.fmtLong2DateTime(dayData[j].dayDate, 'dd')) === i) {
              temp = { ...temp, ...dayData[j] }
              break
            }
          }
          oneDay.push(temp)
        }
        tableData.push(oneDay)
      })

      this.tableData = tableData
    },
    // 百分比转换
    percentageConversion(num) {
      if (num) {
        return num.toFixed(2) + '%'
      }
    },
    //获取窗口高度
    getWinHeight() {
      let that = this
      this.heightL = window.innerHeight - 220
      window.addEventListener('resize', () => {
        that.heightL = window.innerHeight - 270
      })
    },

    // 导出
    exportEcx() {
      // console.log('dayArrtable', JSON.stringify(this.$refs.dayArrtable))
      // console.log('dayArrtacolumnsble', this.$refs.dayArrtable.columns)
      // var headerlist = []
      // for (let index = 0; index < this.$refs.dayArrtable.columns.length; index++) {
      //   const element = this.$refs.dayArrtable.columns[index];
      //   headerlist.push({ name: element.label, key: element.property })
      // }

      // exportExecl(this, headerlist, this.tableData, '列表', new Date().toLocaleDateString() + '导出的列表')
      this.exportExceldata(new Date().toLocaleDateString() + '导出的列表', 'tablearrdata')
    },

    exportExceldata(filename, tableId) {
      var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
      var table = document.querySelector("#" + tableId).cloneNode(true);
      var wb = XLSX.utils.table_to_book(table, xlsxParam);
      /* 获取二进制字符进行输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          filename + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    },
    KeepTwo(data) {
      if (data) {
        return data.toFixed(2)
      } else {
        return ''
      }

    }
  }
}
</script>

<style>
.occupy-black {
  background-color: #F5F7FA !important;
  border-bottom: #F5F7FA !important;
}
</style>
